package language

import (
	"errors"

	"gddgame.cc/galaxy/common/dsl/game"
	"gddgame.cc/galaxy/utils/orm"
)

type LanguageData struct {
	Languages    []SettingLanguage
	LanguageList []*LanguageInstance

	env              *game.Environment
	languageModel    *orm.Model
	languageProvider *game.DataProvider
}

func GetLanguageData(env *game.Environment) (*LanguageData, error) {
	var err error
	data := &LanguageData{env: env}

	if data.languageModel, data.Languages, err = getLanguageData(env); err != nil {
		return nil, err
	}
	data.languageProvider = &game.DataProvider{
		Name:     "language",
		Language: true,
		Array:    false,
		Get: func() (provides interface{}, err error) {
			return data.LanguageList, nil
		},
	}
	env.RegisterData(data.languageProvider)
	data.LanguageList = make([]*LanguageInstance, len(data.Languages))
	for index := range data.Languages {
		data.LanguageList[index] = NewLanguage(data.languageProvider, &data.Languages[index])
	}

	return data, err
}

func (data *LanguageData) LanguageKey(key string) string {
	return data.languageProvider.LanguagePrefix(key)
}

func (data *LanguageData) LanguageError(key string) error {
	return errors.New(data.LanguageKey(key))
}

func getLanguageData(env *game.Environment) (*orm.Model, []SettingLanguage, error) {
	var err error

	model, err := env.GetModel(SettingLanguageName)
	if err != nil {
		return nil, nil, err
	}
	var language []SettingLanguage
	_, err = model.Query().Find(&language)
	if err != nil {
		return nil, nil, err
	}
	return model, language, nil
}
